import { loginApi } from '@/api';
import { APPTOKENKEY, BASEAUTHTOKENFROMSBT, BASETOKENFROMSBT } from '@/common';
import ViewLoading from '@/components/ViewLoading';
import { LoginEnt } from '@/models/LoginEnt';
import { LoginUser } from '@/models/LoginUser';
import { loginEntSlice } from '@/redux/toolkitSlice/LoginEntSlice';
import { loginUserSlice } from '@/redux/toolkitSlice/LoginUserSlice';
import { App } from 'antd';
import { useCallback, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import CodeLogin from './CodeLogin';
import OStyle from './index.less';
import type { BaseLoginProps } from './interface';
import PwdLogin from './PwdLogin';

const LOGINTABLIST = [
  { label: '密码登录', key: 'password' },
  { label: '验证码登录', key: 'code' },
];

function Login() {
  const { message } = App.useApp();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [loginType, setLoginType] = useState<'password' | 'code' | string>('password');
  const [loading, setLoading] = useState(false);

  const loginSuccess = useCallback<BaseLoginProps['onSuccess']>((data) => {
    setLoading(true);
    console.log('--login--登录成功--data--:', data);
    const loginEnt = data.loginEnt;
    // sbt项目 authLogin 返回的token，authToken, 用于调用一些基础数据接口
    localStorage.setItem(BASETOKENFROMSBT, data.token);
    localStorage.setItem(BASEAUTHTOKENFROMSBT, data.authToken);
    if (loginEnt) {
      // 有企业信息
      dispatch(
        loginEntSlice.actions.updateLoginEnt(
          new LoginEnt({
            ...loginEnt,
            organizationType: ['government', 'association'].includes(loginEnt.entTypeCode) ? 1 : 0,
          }),
        ),
      );
    }

    const { entId } = loginEnt;

    loginApi
      .getSafeToken(entId, data.personId)
      .then((res: any) => {
        const { code, message: msg } = res;
        if (code === '200') {
          message.success('登录成功');
          localStorage.setItem(APPTOKENKEY, res.data);
          loginApi
            .getUserRole(entId, data.personId)
            .then((uRes: any) => {
              if (uRes.code === '200') {
                const loginUser = new LoginUser({ ...data, loginRole: uRes.data });
                dispatch(loginUserSlice.actions.updateLoginUser(loginUser));
                navigate('/');
              }
            })
            .catch((err) => {
              setLoading(false);
              console.log('--Login--getUserRole--err--:', err);
            })
            .finally(() => {
              setLoading(false);
            });
        }
      })
      .catch((err) => {
        setLoading(false);
        console.log('--Login--getSafeToken--err--:', err);
      });
  }, []);

  return (
    <div className={OStyle.login_page}>
      <ViewLoading show={loading} />
      <div className={OStyle.login_form_box}>
        <div className={OStyle.login_form_left}></div>
        <div className={OStyle.login_form_right} style={{ padding: '85px 0 0 0' }}>
          <div className={OStyle.logo_text}>安全教育培训平台</div>
          <div className={OStyle.login_tab_list}>
            {LOGINTABLIST.map((item) => (
              <li
                key={item.key}
                onClick={() => setLoginType(item.key)}
                className={item.key === loginType ? OStyle.actives : ''}
              >
                {item.label}
              </li>
            ))}
          </div>
          {loginType === 'password' ? <PwdLogin onSuccess={loginSuccess} /> : <CodeLogin onSuccess={loginSuccess} />}
        </div>
      </div>
    </div>
  );
}

export default Login;
